package com.skit.main.adapter

import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.youth.banner.adapter.BannerAdapter

/**
 * @author shuike <a href="mailto:shuike007@gmail.com">Contact me.</a>
 * @version 1.0
 * @since  2020/5/19
 */
class MainBannerAdapter(list: MutableList<String>, val bitmapAddToMap: Boolean = false) :
    BannerAdapter<String, MainBannerAdapter.ViewHolder>(
        list
    ) {
    private lateinit var bitmaps: MutableMap<Int, Bitmap>

    init {
        if (bitmapAddToMap) {
            bitmaps = mutableMapOf()
        }
    }

    class ViewHolder(val imageView: ImageView) : RecyclerView.ViewHolder(imageView) {

    }

    override fun onCreateHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
        val imageView = ImageView(parent!!.context)
        //注意，必须设置为match_parent，这个是viewpager2强制要求的
        //注意，必须设置为match_parent，这个是viewpager2强制要求的
        imageView.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        imageView.scaleType = ImageView.ScaleType.CENTER_CROP
        return ViewHolder(imageView)
    }

    override fun onBindView(holder: ViewHolder?, data: String?, position: Int, size: Int) {
//        Glide.with(holder!!.imageView).load(data).into(holder.imageView)
        if (bitmapAddToMap) {
            Glide.with(holder!!.imageView).load(data).into(object : CustomTarget<Drawable>() {
                override fun onResourceReady(
                    resource: Drawable,
                    transition: Transition<in Drawable>?
                ) {
                    holder.imageView.setImageDrawable(resource)
                    (resource as BitmapDrawable).also {
                        bitmaps[position] = it.bitmap
                    }
                }

                override fun onLoadCleared(placeholder: Drawable?) {}
            })
        } else {
            Glide.with(holder!!.imageView).load(data).into(holder.imageView)
        }
    }

    fun getBitmap(position: Int): Bitmap? = bitmaps[position]

}